package com.garden.rocketmq.learn.demo.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 消费者 消费信息
 * Created by Garden on 2020/7/22.
 */
public class Consumer {

    public static void main(String[] args) throws MQClientException {
        //实例化消费者Consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group");
        //设置NameServer的地址，Consumer启动后通过NameServer获取目标Topic的路由信息
        consumer.setNamesrvAddr("localhost:9876");
        //订阅消息，可订阅一个或多个Topic以及通过Tag过滤消息
        consumer.subscribe("test_topic","*");
        //注册回调实现类来处理从broker拉取回来的消息
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                // 标记该消息已经被成功消费
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动Consumer实例
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }

}
